import java.net.*;

public class ReliableUDPClient {
    private static final int PACKET_SIZE = 1024;

    public static void main(String[] args) {
        DatagramSocket clientSocket = null;

        try {
            clientSocket = new DatagramSocket();
            InetAddress serverAddress = InetAddress.getByName("localhost");
            int serverPort = 9876;

            int sequenceNumber = 0;

            while (true) {
                // Prepare packet
                String message = "Hello, server! Seq: " + sequenceNumber;
                byte[] sendData = new byte[PACKET_SIZE];
                sendData[0] = (byte) sequenceNumber;
                System.arraycopy(message.getBytes(), 0, sendData, 1, message.length());

                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, serverPort);
                clientSocket.send(sendPacket);

                // Receive acknowledgment
                byte[] ackData = new byte[1];
                DatagramPacket ackPacket = new DatagramPacket(ackData, ackData.length);
                clientSocket.receive(ackPacket);

                int ackSequenceNumber = ackData[0];
                if (ackSequenceNumber == sequenceNumber) {
                    System.out.println("Acknowledgment received for seq " + sequenceNumber);
                    sequenceNumber++;
                } else {
                    System.out.println("Received acknowledgment with incorrect sequence number. Retransmitting...");
                }

                Thread.sleep(1000); // Simulate some delay
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (clientSocket != null && !clientSocket.isClosed()) {
                clientSocket.close();
            }
        }
    }
}

